package proj.pt.web;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Course;
import proj.pt.model.Department;
import proj.pt.model.SubCourse;

public class CourseController extends CustomSimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		// getting the id from the request, if it is supplied as parameter.
		// else -1 will be set.
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		
		// if id value is greater than -1, then requesting to lead an already existing from database,
		// else create a new object.
		Course course = null;
		if(id > -1){
			// load from database
			course = getLogicProcessor().getCourse(new Long(id));
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so  will be null;
		if(course == null)
		return new Course();
		else return course;
	}
	
	
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		List batches = getLogicProcessor().getBatches();
		dataMap.put("batches", batches);
		dataMap.put("batchSize", batches.size());
		dataMap.put("departments", getLogicProcessor().getDepartments());
		return dataMap;
	} //end referenceData
	
	
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Department.class, new DepartmentEditor(getLogicProcessor()));
	}
	
	
	
	
	protected void onFormChange(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)  throws Exception {
		
		String action = WebUtils.getAction(request);
		
		if("action_add".equals(action)){
			String sbcourseName = WebUtils.getStringParameter(request, "scname");
			String sbCourseId = WebUtils.getStringParameter(request, "scId");
			String sbCourseDesc = WebUtils.getStringParameter(request, "scdescription");
			
			if(!StringUtils.hasLength(sbcourseName)){
				errors.reject("semesterName.required", "Semester Name required.");
			} else if(!StringUtils.hasLength(sbCourseId)){
				errors.reject("semesterId.required", "Semester ID required.");
			} else if(!getLogicProcessor().validateSubCourseId(sbCourseId)){
				errors.reject("semesterId.exist", "Semester ID exist, please provide a different ID.");
			} else {
				Course course = (Course)command;
				SubCourse semester = new SubCourse();
				semester.setName(sbcourseName);
				semester.setSubCourseId(sbCourseId);
				semester.setDescription(sbCourseDesc);
				semester.setCreatedDate(new Date());
				semester.setCourse(course);
				course.getSubCourse().add(semester);
			} //end else
			
			if(errors.getErrorCount() > 0){
				request.setAttribute("semName", sbcourseName);
				request.setAttribute("semId", sbCourseId);
				request.setAttribute("semDescription", sbCourseDesc);
			}
			
		} else if("action_remove".equals(action)){
			String selectionValue = WebUtils.getStringParameter(request, "selection_value");
			if(StringUtils.hasText(selectionValue)){
				Course course = (Course)command;
				SubCourse sc = null;
				for(Iterator itr = course.getSubCourse().iterator(); itr.hasNext();){
					sc = (SubCourse)itr.next();
					if(sc != null && selectionValue.equals(sc.getReferenceId())){
						itr.remove();
						break;
					} //end if
				} //end for	
			} //end if
		} //end else if
	}
	
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// f no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		Course course = (Course)command;
		
		if(!StringUtils.hasLength(course.getName())){
			errors.reject("courseName.required", "Course Name required.");
		} //end if
		
		
		// look for course Id 
		if(!StringUtils.hasLength(course.getCourseId())){
			errors.reject("courseId.required", "Course ID required.");
		} else {
			// look for course ID already exist or not.
			if(!getLogicProcessor().validateCourseId(course)){
				errors.reject("courseId.exist", "Course ID exists, please enter a unique ID.");
			} //end if
		}
		
		if(course.getDepartment() == null){
			errors.reject("department.required", "Please select a department.");
		} //end if
		
		if(course.getBatch() == null || course.getBatch().size() < 1){
			errors.reject("batch.required", "Please select the batches.");
		} //end if
				
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String action = WebUtils.getAction(request);
					
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateCourse((Course)command);
		} else if("action_delete".equals(action)){
			getLogicProcessor().deleteCourse((Course)command);
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
		
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit	
	
}
